import { defineStore } from 'pinia'
import { reactive } from 'vue'

export const useLoading = defineStore(
  'LoadingStore',
  () => {
    const loading = reactive({
      state: false,
      reload: false,
      newList: false
    })

    /**
     *
     * @param {Array} data
     * @param {Number} total
     * @returns {boolean}
     */
    const hasMore = function(data = [], total) {
      return total - data.length > 0
    }

    /**
     *
     * @param {Array} data
     * @param {Number} total
     * @returns {boolean}
     */
    const isLoadMore = function(data = [], total) {
      const _hasMore = hasMore(data, total)
      const _loadMore = _hasMore && !loading.reload

      if (loading.newList) {
        return false
      }
      return _loadMore
    }

    const SET_LOADING = function() {
      loading.state = true
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }

    const SET_RELOAD = function() {
      loading.reload = true
    }

    const FINISH_ALL = function() {
      loading.state = false
      loading.reload = false
      loading.newList = false
      uni.hideLoading()
    }

    const NEW_LIST = function() {
      loading.newList = true
    }
    const LOAD_LIST = function() {
      loading.newList = false
    }
    return {
      isLoadMore,
      hasMore,
      ILOADING: loading.state,
      IRELOAD: loading.reload,
      SET_LOADING,
      FINISH_ALL,
      SET_RELOAD,
      NEW_LIST,
      LOAD_LIST
    }
  })
